import os
import time
import platform
from datetime import datetime
import cpu


def high_cpu_load_test(n_terms):
    """
    高算力消耗测试：计算圆周率π的值，并显示进度
    参数：
    - n_terms: 计算项数
    """
    print("2、开始浮点运算测试（计算圆周率π的值）...")
    start_time = time.time()

    def calculate_pi(n_terms):
        numerator = 4.0
        denominator = 1.0
        operation = 1.0
        pi = 0.0
        for i in range(n_terms):
            pi += operation * (numerator / denominator)
            denominator += 2.0
            operation *= -1.0

            # 显示进度
            progress = (i + 1) / n_terms * 100
            elapsed = time.time() - start_time
            print(f"进度: {progress:.2f}%, 已用时: {elapsed:.2f}秒, 当前π值: {pi}", end="\r")

        return pi

    pi_value = calculate_pi(n_terms)

    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"\n计算完成！π值: {pi_value}")
    return elapsed_time


def high_integer_load_test(n_terms, base=2, exponent=1000000, modulus=10 ** 9 + 7):
    """
    高整数运算测试：模幂运算
    参数：
    - n_terms: 运算重复次数
    - base: 底数
    - exponent: 指数
    - modulus: 模数
    """
    print("1、开始整数运算测试（模幂运算）...")
    start_time = time.time()

    def modular_exponentiation(base, exponent, modulus):
        result = 1
        base = base % modulus  # 确保底数小于模数
        while exponent > 0:
            if exponent % 2 == 1:  # 如果指数是奇数
                result = (result * base) % modulus
            base = (base * base) % modulus
            exponent //= 2
        return result

    for i in range(n_terms):
        modular_exponentiation(base, exponent, modulus)

        # 显示进度
        progress = (i + 1) / n_terms * 100
        elapsed = time.time() - start_time
        print(f"进度: {progress:.2f}%, 已用时: {elapsed:.2f}秒", end="\r")

    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"\n计算完成！")
    return elapsed_time


def generate_report(info, float_test_time, integer_test_time):
    """生成测试报告，并显示报告内容"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report_filename = f"测试报告_{timestamp}.txt"
    with open(report_filename, "w") as f:
        f.write("性能测试报告\n")
        f.write("=" * 30 + "\n")
        f.write(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"{info[0]} \n")
        f.write(f"{info[1]} \n")
        f.write(f"{info[2]} \n")
        f.write(f"----------------\n")
        f.write(f"整数运算测试耗时: {integer_test_time:.2f}秒\n")
        f.write(f"浮点运算测试耗时: {float_test_time:.2f}秒\n")
        f.write("\n测试完成！\n")

    # 打印报告内容到控制台
    print("\n测试报告内容如下：")
    print("=" * 30)
    with open(report_filename, "r") as f:
        print(f.read())
    print("=" * 30)

    print(f"测试报告已生成: {report_filename}")


if __name__ == "__main__":
    # 获取系统信息
    info=[cpu.get_cpu_info(),cpu.get_memory_info(),cpu.get_os_info()]
    for l in info:
        print(l)
    print()

    # 定义测试循环次数
    n_terms1 = 10 ** 13  # 测试项数
    n_terms2 = 3 * 10 ** 7  # 测试项数

    # 高整数运算测试
    integer_test_time = high_integer_load_test(n_terms=n_terms1 // 1000000, base=2, exponent=1000000,
                                               modulus=10 ** 9 + 7)

    # 高算力消耗测试：浮点运算
    float_test_time = high_cpu_load_test(n_terms=n_terms2)

    # 生成测试报告
    generate_report(info, float_test_time, integer_test_time)